package com.kfm.base.thread.day03;

public class Demo16 {

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            Singleton s = Singleton.getSingleton();
            System.out.println("Thread 1: " + s.name + ", " + s.age);
        });

        Thread thread2 = new Thread(() -> {
            Singleton s = Singleton.singleton;
            if (s !=null)
            System.out.println("Thread 2: " + s.name + ", " + s.age);
        });

        thread1.start();
        thread2.start();
    }
}

class Singleton {

    public String name;
    public int age;

    public static volatile Singleton singleton;

    public Singleton(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            singleton = new Singleton("张安", 22);
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return singleton;
    }

}
